<template>
  <div>
    <scroll-view
      class="nearby-list"
      :scroll-y="true"
      @scrolltolower="handleNearbyListNextPage"
    >
      <block v-if="tableData.length > 0">
        <view
          v-for="item in tableData"
          :key="item.id"
          class="nearby-list-item"
          @click="handleGetNearbyLocation(item)"
        >
          <view class="nearby-list-item-left">
            <view class="left-title">{{ item.address }}</view>
            <view class="left-content">
              <text>{{ item.userName }}</text>
              <text>{{ item.phone }}</text>
            </view>
          </view>
          <view class="nearby-list-item-right">
            <u-radio-group
              v-model="currentNearbyId"
              @change="handleGetNearbyLocation(item)"
            >
              <u-radio :activeColor="themeColor" :name="item.id"></u-radio>
            </u-radio-group>
          </view>
        </view>
        <view class="nearby-list-item"> </view>
      </block>
      <view v-else @click="handleToAddEditAddress" class="list-empty">
        <list-empty
          :iconUrl="require('@/pages/sp-address/images/no-address.png')"
          title="暂无收货地址，请点击尝试添加收货地址"
        />
      </view>
    </scroll-view>
  </div>
</template>

<script>
import { mapState } from "vuex";
import listEmpty from "@/components/baseComponents/list-enpty";
import { getAddressList } from "@/service/api/sp-address";
import { TENCENT_MAP_KEY } from "@/const/address/key";

export default {
  name: "nearbyList",
  components: { listEmpty },
  props: {
    currentId: {
      type: String,
      default: "0",
    },
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
  },
  watch: {
    currentId(val) {
      // console.log("更新currentId", val);
      this.currentNearbyId = val;
    },
  },
  created() {
    this.currentNearbyId = this.currentId;
    this.innit();
  },
  data() {
    return {
      currentNearbyId: 0,
      tableData: [],
    };
  },
  methods: {
    async innit() {
      const data = await getAddressList();
      data?.map((v) => {
        v.address = v.province + v.city + v.country + v.street + v.detail;
        const info = this.handleGetLocation(v);
        Promise.all([info]).then((p) => {
          // console.log("======", p);
          v.info = p[0];
          v.id = v.info?.address_reference?.landmark_l2?.id;
        });
        // console.log(v);
        return v;
      });
      this.tableData = data;
    },
    handleNearbyListNextPage() {
      this.$emit("next-page");
    },
    handleChangeCurrentNearby(item) {
      this.handleGetNearbyLocation(item);
    },
    handleGetLocation(query) {
      if (!query) return;
      return new Promise((resolve) => {
        const { latitude = 0, longitude = 0 } = query;
        uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${TENCENT_MAP_KEY}`,
          success: (res) => {
            resolve(res?.data?.result);
          },
        });
      });
    },
    handleGetNearbyLocation(query) {
      if (!query) return;
      const { latitude = 0, longitude = 0 } = query;
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${TENCENT_MAP_KEY}`,
        success: (res) => {
          const {
            statusCode,
            data: {
              status,
              result: {
                address_reference: { landmark_l2 },
                ad_info: { city },
                address,
              },
            },
          } = res;
          if (statusCode === 200 && status === 0) {
            this.$emit("update:region", city);
            const params = {
              latitude: query.latitude,
              longitude: query.longitude,
              address,
              title: landmark_l2.title,
              distance: landmark_l2._distance,
            };
            this.$store.dispatch(
              "sp-address/location/setCurrentLocation",
              params
            );

            this.$emit("update:currentId", landmark_l2.id);
            this.$emit("handleUpdateCurrentId", {
              location: {
                lat: query.latitude,
                lng: query.longitude,
              },
              id: landmark_l2.id,
            });
            this.$emit("handleSetCover", {
              id: Number(landmark_l2.id),
              strId: landmark_l2.id,
              latitude: query.latitude,
              longitude: query.longitude,
              iconPath: "/static/images/address-1.png",
              width: 25,
              height: 25,
              callout: {
                content: landmark_l2.title,
                color: "#888888",
                fontSize: 14,
                display: "ALWAYS",
                bgColor: "#fff",
                padding: 10,
              },
            });

            this.$nextTick(() => {
              this.$Router.back();
            });
          }
        },
      });
    },
    handleToAddEditAddress() {
      this.$Router.push({
        name: "myEditAddress",
        params: {
          type: "add",
        },
      });
    },
  },
};
</script>

<style scoped lang="scss">
.nearby-list {
  height: calc(
    100vh - 84rpx - 537rpx - 108rpx - 182rpx - env(safe-area-inset-bottom)
  );
  &-item {
    padding: 32rpx 33rpx;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #ececec;
    &:last-child {
      height: 180rpx;
      border-bottom: none;
    }
    &-left {
      flex: 1;
      .left-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #181818;
      }
      .left-content {
        margin-top: 19rpx;
        font-size: 29rpx;
        font-weight: 500;
        color: #888888;
        text:last-child {
          margin-left: 5px;
        }
      }
    }
    &-right {
    }
  }
  .list-empty {
    margin-top: 100rpx;
  }
}
</style>
